#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <sys/wait.h>
using namespace std;

int main()
{
    //1.父进程创建管道
    int pipefd[2]={0};
    int n=pipe(pipefd);
    (void)n;
    //2.通过fork创建子进程
    int id=fork();
    if(id < 0)
    {
        perror("fork");
        exit(1);
    }
    else if(id == 0)
    {
        //3.父子进程关闭相应的读写端
        //子进程
        //子进程关闭读端
        close(pipefd[0]);
        int cnt=0;
        while(true)
        {
            string str="hello hello, 我是子进程";
            string self=to_string(getpid());
            string message = str + ", "+ self + ", ";
            message += to_string(cnt++);
            write(pipefd[1],message.c_str(),message.size());
            sleep(3);
        }
    }
    else
    {
        //3.父子进程关闭相应的读写端
        //父进程
        //父进程关闭写端
        close(pipefd[1]);
        while(true)
        {
            char buffer[1024]={0};
            ssize_t n=read(pipefd[0],buffer,sizeof(buffer)-1);
            if(n > 0)
            {
                buffer[n]=0;
                cout << "client->father " << buffer << endl;
            }
        }
    }

    //4.传递数据
    pid_t rid=waitpid(id,nullptr,0);
    (void)rid;
    return 0;
}

























// int main()
// {
//     int pipefd[2]={0};
//     int n=pipe(pipefd);
//     if(n == 0)
//     {
//         printf("pipe success, pipefd[0] = %d,pipefd[1] = %d\n",pipefd[0],pipefd[1]);
//     }
//     return 0;
// }

